package main

import (
	"fmt"
	"time"
	"math/rand"
)

var sem=make(chan interface{}, 10)

type Request struct {
	a,b int
	reply chan int
}

func process(r *Request) {
	time.Sleep(time.Second*time.Duration(rand.Float64()*5))
	r.reply <- r.a + r.b
}

func handler(r *Request) {
	fmt.Println(r)
	process(r)
	<-sem
}

func server(reqs chan *Request) {
	for {
		sem<-1
		req:= <-reqs
		go handler(req)
	}
}

func main() {
	reqs:=make(chan *Request)
	go server(reqs)

	go func () {
		for i:=0;;i++ {
			req:=Request{i,i,make(chan int,1)}
			reqs <- &req
		}
	}()

	time.Sleep(time.Second*100)
}
